/**
 * Index
 * @file 公示公开
 * @module src/pages/PublicOpen/index.tsx
 * @author yunqilaohe
 */

import React, { useEffect, useState } from 'react';
import styles from './index.less';
import { Input, Breadcrumb, Select, DatePicker, Row, Col } from 'antd';
import PolicyRadio from '@/pages/components/PolicyRadio';
import ProTable, { ProColumns } from '@ant-design/pro-table';
import { getPolicyResultData, getResultPublicity } from '@/services/homePage/homePage';
import { useModel } from 'umi';
import type { PolicyOrganizationsState } from '@/models/common';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';

const { RangePicker } = DatePicker;

const { Search } = Input;
const { Option } = Select;

const examinationColumns: ProColumns<any>[] = [
  {
    title: '事项',
    dataIndex: 'title',
    render: (_, entity) => {
      return (
        <a target="_blank" className={styles.listItemTitle} href={entity?.fileUrl}>
          {entity.title}
        </a>
      );
    },
  },
  {
    title: '发布时间',
    dataIndex: 'publishTime',
    width: 180,
  },
  {
    title: '业务部门',
    dataIndex: 'publishOrgName',
    width: 120,
  },
];

const resultsColumns: ProColumns<any>[] = [
  {
    title: '申请编号',
    dataIndex: 'applyNo',
    width: 100,
  },
  {
    title: '申请时间',
    dataIndex: 'applyTime',
    width: 120,
  },
  {
    title: '处理状态',
    dataIndex: 'currentAuditNode',
    width: 80,
    render: (text: string) => {
      if (text === '0') return '企业申请';
      if (text === '1') return '主管部门初审';
      if (text === '2') return '政策兑现办审核';
      if (text === '3') return '主管部门复审';
      if (text === '4') return '园区终审';
      if (text === '5') return '财政终审';
      if (text === '6') return '园区公示拨付';
      if (text === '7') return '已拨付';
      return '中止';
    },
  },
  {
    title: '处理时间',
    dataIndex: 'currentAuditTime',
    width: 120,
  },
];

interface HeaderProps {
  title: string;
}

const Header = (props: HeaderProps) => {
  const { title } = props;
  return (
    <div className={styles.rightHeader}>
      <div className={styles.headerLeft}>
        <div className={styles.dot} />
        <div className={styles.headerTitle}>{title}</div>
      </div>
    </div>
  );
};

interface SearchOrSelectProps {
  title?: string;
  children?: React.ReactNode;
  searchPlaceholder: string;
  onSearch: (text: string) => void;
}

const SearchOrSelect = (props: SearchOrSelectProps) => {
  const { title, children, searchPlaceholder, onSearch } = props;
  return (
    <Row gutter={5} justify={'end'} align={'middle'} style={{ height: 50, width: '100%' }}>
      <Col>{title}</Col>
      <Col span={title === '业务部门' ? 4 : 8}>{children}</Col>
      <Col span={6}>
        <Search
          placeholder={searchPlaceholder}
          onSearch={onSearch}
          enterButton
          className={styles.searchInput}
        />
      </Col>
    </Row>
  );
};

const RenderApprovalProTable = ({
  policyOrganizations,
}: {
  policyOrganizations: PolicyOrganizationsState[];
}) => {
  const [requestParams, setRequestParams] = useState({
    title: '',
    publishOrg: null,
    page: 0,
    size: 10,
  });
  return (
    <>
      <Header title={'审批公示'} />
      <SearchOrSelect
        title={'业务部门'}
        searchPlaceholder={'请输入事项名称'}
        onSearch={(text) => {
          setRequestParams({ ...requestParams, title: text });
        }}
      >
        <Select
          style={{ width: '100%' }}
          placeholder="全部"
          onChange={(value) => {
            setRequestParams({ ...requestParams, publishOrg: value as any });
          }}
          allowClear
          className={styles.SelectDept}
        >
          {policyOrganizations?.length &&
            policyOrganizations?.map((obj) => {
              return (
                <Option key={obj.id} value={obj.id}>
                  {obj.orgName}
                </Option>
              );
            })}
        </Select>
      </SearchOrSelect>
      <ProTable
        className={styles.proTable}
        columns={examinationColumns}
        params={requestParams}
        request={async () => {
          const { results = [], totalCount = 0 } = await getPolicyResultData(requestParams);
          return {
            data: results,
            total: totalCount,
            success: true,
          };
        }}
        rowKey={'id'}
        pagination={{
          showQuickJumper: true,
          pageSize: requestParams?.size || 10,
          current: requestParams?.page || 1,
          onChange: (pIndex, pSize) => {
            setRequestParams({ ...requestParams, page: pIndex, size: pSize as number });
          },
        }}
        options={false}
        search={false}
        headerTitle={false}
        toolBarRender={() => []}
      />
    </>
  );
};

const RenderResultsProTable = () => {
  const [requestParams, setRequestParams] = useState({
    applyStartTime: '',
    applyEndTime: '',
    applyNo: '',
    page: 0,
    size: 10,
  });

  return (
    <>
      <Header title={'结果公示'} />
      <SearchOrSelect
        title={'申请时间'}
        searchPlaceholder={'请输入申请编号'}
        onSearch={(text) => {
          setRequestParams({ ...requestParams, applyNo: text });
        }}
      >
        <RangePicker
          format={'YYYY-MM-DD HH:mm:ss'}
          locale={locale}
          showTime
          onChange={(dates, dateStrings) => {
            setRequestParams({
              ...requestParams,
              applyStartTime: [...dateStrings].shift() as string,
              applyEndTime: [...dateStrings].pop() as string,
            });
          }}
        />
      </SearchOrSelect>
      <ProTable
        className={styles.proTable}
        columns={resultsColumns}
        params={requestParams}
        request={async () => {
          const { results, totalCount } = await getResultPublicity(requestParams);
          return {
            data: results,
            total: totalCount,
            success: true,
          };
        }}
        rowKey={'id'}
        pagination={{
          showQuickJumper: true,
          pageSize: requestParams?.size || 10,
          current: requestParams?.page || 1,
          onChange: (pIndex, pSize) => {
            setRequestParams({ ...requestParams, page: pIndex, size: pSize as number });
          },
        }}
        options={false}
        search={false}
        headerTitle={false}
        toolBarRender={() => []}
      />
    </>
  );
};

const PublicOpen = () => {
  const [publicOpenRadio, setPublicOpenRadio] = useState('01');
  const isApproval: boolean = publicOpenRadio === '01';

  const { policyOrganizations, getPolicyOrganizations } = useModel('common', (model) => ({
    policyOrganizations: model.policyOrganizations,
    getPolicyOrganizations: model.getPolicyOrganizations,
  }));

  useEffect(() => {
    getPolicyOrganizations();
  }, []);

  return (
    <div className={styles.container}>
      <div className={styles.applyHeader}>
        <p className={styles.title}>公示公开</p>
        <p className={styles.subTitle}>/全面囊括政策信息</p>
      </div>
      <div className={styles.content}>
        <div className={styles.breadcrumb}>
          <Breadcrumb separator="">
            <Breadcrumb.Item>您的位置</Breadcrumb.Item>
            <Breadcrumb.Separator>:</Breadcrumb.Separator>
            <Breadcrumb.Item href="">首页</Breadcrumb.Item>
            <Breadcrumb.Separator />
            <Breadcrumb.Item>公示公开</Breadcrumb.Item>
          </Breadcrumb>
        </div>
        <div className={styles.tableContent}>
          <PolicyRadio
            defaultValue={'01'}
            dataSource={[
              { title: '审批公示', code: '01' },
              { title: '结果公示', code: '02' },
            ]}
            onChange={(e) => {
              setPublicOpenRadio(e.target.value);
            }}
          />
          <div className={styles.policyRight}>
            {isApproval ? (
              <RenderApprovalProTable policyOrganizations={policyOrganizations} />
            ) : (
              <RenderResultsProTable />
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default PublicOpen;
